<template>
  <div class="container">
    <FmTable  @queryDataFunction="loadTable" :queryDataSelf="true" ref="fmTable" url="/process/generator" id="id" tableName="templateconfig"  :columns="columns"
              :toolbar="['add','del']">
      <template #opt="scope">
                    <el-button link size="small" type="primary" @click="onTableUpdate(scope.row)">修改</el-button>
                    <el-button link size="small" type="primary" @click="onTableCopy(scope.row)">复制</el-button>

      </template>

    </FmTable>
  </div>
</template>

<script setup lang="ts">
import JSZip from 'jszip'
import {saveAs} from 'file-saver'
import {fetchData, delData, saveorUpadateDate, deteleAllData} from '@/api';
import {ref, reactive, onMounted} from "vue";
import {useRoute, useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";

const CUR_GROUP_ID_KEY = 'gen.cur.groupid'
let router = useRouter()
let route=useRoute()
let activeName = ref('')
let tableData = ref([])
let groupData = ref([])
let groupTitle=ref('')
let currentTab = ref({id: 0})
let importDialogVisible = ref(false)
let importLoading = ref(false)
let importFiles = ref([])
let fmTable=ref();
const columns=[
  {
    "label": "模板编号",//标签名称
    "index": "id",//数据库索引
    "rules": [
      {required: true, message: "请输入主键", trigger: "blur",},
    ],//值规则
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
    "addable": false
  },
  {
    "label": "模板名称",//标签名称
    "index": "groupName",//数据库索引
    "rules": [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],//值规则
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "label": "文件名称",//标签名称
    "index": "fileName",//数据库索引
    "rules": [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],//值规则
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "type": "opt",//普通行，字典行，自定义行
    "label": "操作",//标签名称
    "index": "opt",//数据库索引
    "rules": [],//值规则
    "width": 150,
    "dataType": "text",//值值类型默认字符类型
  }
]

const loadTable = (pageDto,callback):any => {
 let groupId=route.query.groupId
  if(groupId!=undefined){
    pageDto["groupId"]=groupId
  }
  fetchData(`/process/generator/templateconfig/list`, pageDto).then(resp => {
    callback(resp)

  })
}
const handleClick = (tab: any) => {
  const id = parseInt(tab.name)
  if (id) {
    selectTab(parseInt(id))
  }
}
const onTableUpdate = (row: any) => {
  router.push({
    path: `/admin/tool/generate/templateedit`, query: {
      id: row.id
    }
  })
}
const onTableCopy = (row: any) => {
  let currentGroup = currentTab.value;
   groupTitle.value = `确认要复制【${row.name}】吗？`
  ElMessageBox.confirm('请输入复制后的模板名称', '复制模板', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: row.name + ' Copy',
    inputPattern: /^.{1,64}$/,
    inputErrorMessage: '不能为空且长度在64以内'
  }).then(({value}) => {
    if (value === row.name) {
      ElMessage.error('名称不能重复')
      return
    }
    const data = {
      name: value,
      id: row.id,
      groupName: currentGroup.groupName,
      groupId: currentGroup.groupId
    }
    saveorUpadateDate('/process/generator/templateconfig/copy', data).then(resp => {
      reload()
    })
  }).catch(() => {
  })
}

const onTableDelete= (row:any)=> {
  ElMessageBox.confirm(`确认要删除【${row.name}】吗？`).then(() => {
    saveorUpadateDate('/process/generator/templateconfig/del', row).then(() => {
      reload()
    })
  })
}
const onAdd = () => {
  router.push({
    path: `/admin/tool/generate/templateedit`, query: {
      id: 0,
      groupId: currentTab.value.id
    }
  })
}
// group
const onGroupInfoUpdate = () => {
  onGroupUpdate(currentTab.value)
}
const onGroupInfoDelete = () => {
  onGroupDelete(currentTab.value)
}
const onGroupAdd = () => {
  groupTitle.value = '增加模板组'
  ElMessageBox.confirm('请输入组名称', '增加模板组', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: '',
    inputPattern: /^.{1,64}$/,
    inputErrorMessage: '不能为空且长度在64以内'
  }).then(({value}) => {
    const data = {
      groupName: value
    }
    saveorUpadateDate('/process/generator/templategroup/add', data).then(resp => {
      currentTab.value = resp
      reload()
    })
  }).catch(() => {
  })
}
const onGroupUpdate = (row: any) => {
  ElMessageBox.confirm('请输入组名称', '修改模板组', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: row.groupName,
    inputPattern: /^.{1,64}$/,
    inputErrorMessage: '不能为空且长度在64以内'
  }).then(({value}) => {
    const data = {
      id: row.id,
      groupName: value
    }
    saveorUpadateDate('/process/generator/templategroup/update', data).then(resp => {
      reload()
    })
  }).catch(() => {
  })
}
const onGroupDelete = (row: any) => {
  ElMessageBox.confirm(`确认要删除【${row.groupName}】吗？`).then(() => {
    saveorUpadateDate('/process/generator/templategroup/del', row).then(() => {
      currentTab.value.id = 0
      reload()
    })
  })
}
const onImportTemplates = () => {
  importFiles.value = []
  importLoading.value = false
  importDialogVisible.value = true
}
const onImportDialogClosed = () => {
  if (currentTab) {
    loadTable(currentTab.value.id)
  }
}
const uploadTemplates = (target: any) => {
  importLoading.value = true
  const file = target.file
  importFiles.value.push({
    name: file.name,
    state: "上传中..."
  })
  const reader = new FileReader()
  reader.readAsText(file)
  reader.onloadend = async () => {
    let content = reader.result
    let templateName = file.name
    let splitIdx = templateName.lastIndexOf(".");
    if (splitIdx !== -1) {
      templateName = templateName.substring(0, splitIdx)
    }
    let data = {
      groupId: currentTab.value.id,
      groupName: currentTab.value.groupName,
      name: templateName,
      content: content,
    }
    await saveTemplate(data)
    importFiles.value.forEach(item => {
      if (item.name === file.name) {
        item.state = "成功"
      }
    })
  }
  return true
}
const saveTemplate = (data: any) => {
  const uri = '/process/generator/templateconfig/save'
  saveorUpadateDate(uri, data)
}
const downloadTemplates = () => {
  const folder = currentTab.groupName;
  const filename = folder + ".zip"
  const zip = new JSZip()
  const folderZip = zip.folder(folder)
  tableData.value.forEach(row => {
    folderZip.file(row.name + ".vm", row.content)
  })
  // 下载
  zip.generateAsync({type: 'blob'}).then(function (content) {
    // see FileSaver.js
    saveAs(content, filename)
  })
}
</script>
